<template>
  <view>
    <view class="container">
      <!-- 主表信息卡片 -->
      <view class="info-card">
        <view class="item-field">
          <text class="label">随货同行单编号:</text>
          <text class="value">{{ suihuo.outOrderId }}</text>
        </view>
        <view class="item-field">
          <text class="label">发货时间:</text>
          <text class="value">{{ formatTimestamp(suihuo.createTime) }}</text>
        </view>
      </view>

      <!-- 子表数据列表 -->
      <view v-for="(item, index) in suihuozi" :key="index">
        <view class="info-card">
          <!-- 产品名称 -->
          <view class="horizontal-info1">
            <view class="item-field">
              <text class="label">产品名称:</text>
              <text class="value">{{ item.productName }}</text>
            </view>
		  </view>
		  
          <!-- 产品信息行 -->
          <view class="horizontal-info3">
            <view class="item-field">
              <text class="label">产品批次:</text>
              <text class="value">{{ item.batch }}</text>
            </view>
            <view class="item-field">
              <text class="label">有效期:</text>
              <text class="value">{{ timestampToStr(item.validityDate, 'yyyy-MM-dd') }}</text>
            </view>
            <view class="item-field">
              <text class="label">产品规格:</text>
              <text class="value">{{ item.productStandards }}</text>
            </view>
          </view>
          <view class="horizontal-info3">
            <view class="item-field">
              <text class="label">单价:</text>
              <text class="value">{{ item.productPrice }}</text>
            </view>
            <view class="item-field">
              <text class="label">数量:</text>
              <text class="value">{{ item.count }}</text>
            </view>
            <view class="item-field">
              <text class="label">总价:</text>
              <text class="value">{{ item.totalPrice }}</text>
            </view>
          </view>
		  
          <!-- 入库数量单独一行 -->
          <view class="horizontal-info2">
            <text class="label">入库数量:</text>
            <input
              type="number"
              :value="item.inCount"
              @input="handleStockInQuantityInput($event, index)"
              placeholder="请输入入库数量"
              class="stock-in-input"
            />
          </view>
		  <view class="item-field remark-container">
			<text class="label">备注:</text>
			<input
			  type="text"
			  v-model="item.remark"
			  placeholder="请输入备注"
			  class="remark-input"
			/>
		  </view>
        </view>
      </view>
    </view>

    <!-- 底部留白，避免按钮遮挡内容 -->
    <view class="bottom-spacer"></view>
    
    <!-- 确定按钮（固定在底部） -->
    <view class="button-container">
      <button @click="handleConfirm">确定</button>
    </view>
  </view>
</template>

<script>
import * as SupplierSendOrderApi from '@/api/suppliersendorder/inde.js'; // 随货同行单
import * as SupplierSendOrderItemApi from '@/api/suppliersendorderitem/index.js'; // 随货同行单项
import * as PurPurchaseOrderApi from '@/api/purpurchaseorder/index.js'; // 订单表
import * as PurchaseInOrderApi from '@/api/purchaseinorder/index.js'; // 入库审核单

export default {
  data() {
    return {
      product: '', // 存储扫码传递过来的随货同行单ID
      suihuozi: [], // 随货同行单子项列表
      suihuo: {}, // 随货同行单主表信息
      subTableData: [] // 存储关联的订单表子表数据
    };
  },
  onLoad(options) {
    console.log('传递过来的参数', options.data);
    this.product = options.data;
    this.getList(); 
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        // 1. 获取主表数据
        const ress = await SupplierSendOrderApi.getSupplierSendOrder(this.product);
        this.suihuo = ress.data;
        console.log('主表数据', this.suihuo);

        // 2. 获取关联的订单子表数据（虽然目前未在模板中使用，但保留了逻辑）
        const purchaseOrderId = this.suihuo.purchaseOrderId;
        if (purchaseOrderId) {
          this.subTableData = await this.getOrderSubTableData(purchaseOrderId);
        }

        // 3. 获取随货同行单子项列表
        const res = await SupplierSendOrderApi.getSupplierSendOrderItemListByOutOrderId(this.product);
        this.suihuozi = res.data;
        console.log('子表数据', this.suihuozi);

        // 4. 初始化入库数量为发货数量，备注为空
        this.suihuozi.forEach(item => {
          // 使用 Vue.set 或 this.$set 来确保新增的属性也是响应式的
          this.$set(item, 'inCount', item.count);
          this.$set(item, 'remark', '');
        });
      } catch (error) {
        console.error('获取数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },
    // 通过purchaseOrderId查询订单表的子表数据
    async getOrderSubTableData(purchaseOrderId) {
      try {
        const res = await PurPurchaseOrderApi.getPurPurchaseOrderItemListByPurchaseOrderId(purchaseOrderId); 
        console.log('订单表子表数据', res.data);
        return res.data;
      } catch (error) {
        console.error('查询订单表子表数据失败:', error);
        return [];
      }
    },
    // 时间戳转换方法
    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 灵活的时间戳转换方法
    timestampToStr(timestamp, format = 'yyyy-MM-dd') {
      if (!timestamp || typeof timestamp !== 'number' || timestamp <= 0) {
        return '暂无日期';
      }
      const date = new Date(timestamp);
      if (isNaN(date.getTime())) {
        return '无效日期';
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return format
        .replace('yyyy', year)
        .replace('MM', month)
        .replace('dd', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    },
    // 入库数量输入处理
    handleStockInQuantityInput(event, index) {
      const value = event.target.value;
      // 使用 this.$set 确保视图更新
      this.$set(this.suihuozi[index], 'inCount', Number(value));
    },
    // 处理确定按钮点击事件
    async handleConfirm() {
      // 校验入库数量
      for (let item of this.suihuozi) {
        if (item.inCount > item.count) {
          uni.showToast({
            title: '入库数量不能大于发货数量',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }
      try {
        uni.showLoading({ title: '提交中...', mask: true });
        // 1. 更新随货同行单项的入库数量和备注
        await this.updateSuppliersendOrderItem();
        // 2. 创建入库审核单
        await this.savePurchaseInOrder();
        uni.hideLoading();
        uni.showToast({ title: '操作成功', icon: 'success' });
        // 3. 返回上一页
        setTimeout(() => {
          uni.navigateBack({ delta: 1 });
        }, 1500);
      } catch (error) {
        uni.hideLoading();
        console.error('操作失败:', error);
        uni.showToast({ title: '操作失败，请重试', icon: 'none' });
      }
    },
    // 保存采购入库单数据到数据库
    async savePurchaseInOrder() {
      const data = {
        outOrderId: this.product,
        integrateId: this.suihuo.integrateId,
        purchaseOrderId: this.suihuo.purchaseOrderId,
        supplierId: this.suihuo.deptId, // 假设deptId是供应商ID
        status: 0, // 假设1代表某个状态，如待审核
        dataStatus: 0, // 假设0代表正常状态
      };
      await PurchaseInOrderApi.createPurchaseInOrder(data);
      console.log('采购入库单数据保存成功', data);
    },
    // 更新随货同行单项数据
    async updateSuppliersendOrderItem() {
      // 确保只发送必要的字段
      const itemsToUpdate = this.suihuozi.map(item => ({
        id: item.id,
        inCount: item.inCount,
        remark: item.remark
      }));
      await SupplierSendOrderItemApi.updateSupplierSendOrderItems(itemsToUpdate); 
      console.log('随货同行单项数据更新成功', itemsToUpdate);
    }
  },
};
</script>

<style scoped>
.container {
  margin-top: 10px;
  padding: 0px 10px;
  background-color: #f5f5f5;
}

.info-card {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.horizontal-info1, .horizontal-info2, .horizontal-info3 {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 5px 0;
}

/* .horizontal-info1, .horizontal-info3 {
  margin: 5px 0;
} */

.item-field {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 8px;
  min-width: 30%; /* 确保三列布局时不会挤在一起 */
}

.label {
  font-size: 14px;
  color: #666666;
  margin-bottom: 4px;
}

.value {
  font-size: 15px;
  color: #333333;
  font-weight: 500;
}

/* 输入框样式 */
.stock-in-input {
  background-color: #eeeeee;
  text-align: right;
  margin-right: 10px;
  /* padding: 8px 12px;s */
  border-radius: 4px;
  flex-grow: 1; /* 让输入框占据剩余空间 */
}

.remark-container {
  flex-direction: row;
  align-items: center;
  width: 100%;
}

.remark-input {
  background-color: #eeeeee;
  /* padding: 8px 12px; */
  border-radius: 4px;
  flex-grow: 1;
  margin-left: 10px;
}

/* 底部区域 */
.bottom-spacer {
  height: 80px; /* 为固定底部的按钮留出空间 */
}

.button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #ffffff;
  padding: 10px 0;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.05);
  text-align: center;
  z-index: 999; /* 确保按钮在最上层 */
}

button {
  width: 90%;
  background-color: #007aff;
  color: #ffffff;
  border-radius: 8px;
  font-size: 16px;
}

button::after {
  border: none;
}
</style>
